<?php

namespace App\Dao\Mongodb;

use App\Actions\MessageAction;
use App\Dao\ClosenessDao;
use App\Dao\UserDao;
use App\Dao\UserRemarkDao;
use App\Model\User;
use App\Model\UserRemark;
use App\Utils\LoggerUtil;
use App\Utils\MongoDBClient;
use Hyperf\Context\ApplicationContext;
use Throwable;

class UserChatV2Dao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }

    /**
     * 获取用户未读消息
     * @param $uid
     * @return mixed
     */
    public function getLastMessage($uid)
    {
        $userInfo = User::findUserInfoById($uid);
        $uid = $userInfo['id'];
        try {
            $imei = $userInfo['imei'];
            $data = [];
            $mon = MongoDBClient::getInstance();
            //查找上次拉取数据之后的数据
            $lastMsgWhere['uid'] = (int)$uid;
            $lastMsgWhere['unique'] = (string)$imei;
            $lastMsgOption['limit'] = 1;
            $lastMsg = $mon->find('tb_user_chat_flag', $lastMsgWhere, $lastMsgOption);
            //使用毫秒级
            $micotime = microtime(true);
            $defaultFindMsgTime = $micotime - 86400 * 3;
            $findMsgTime = $defaultFindMsgTime;
            if (!empty($lastMsg)) {
                $lastMsgTime = $lastMsg[0]['last_time'];
                if (15289440240 < $lastMsgTime) {
                    $lastMsgTime = $lastMsgTime / 1000;
                }
                $findMsgTime = max($lastMsgTime, $defaultFindMsgTime);
            }
            $where['receive_uid'] = (int)$userInfo['id'];
            $where['ctime']['$gt'] = $findMsgTime;
            $where['ctime']['$lte'] = $micotime;

            $where['chat_type']['$in'] = [2]; //用户和主播之间的视频音频通话请求
            $where['chat_type']['$in'][] = 4; //用户和用户之间聊天消息
            $where['chat_type']['$in'][] = 7; //用户和主播之间的视频音频通话请求
            $where['chat_type']['$in'][] = 8; //主播群发视频音频通话请求
            $where['chat_type']['$in'][] = 9; //视频语音通话挂断通知
            $where['chat_type']['$in'][] = 10; //视频语音通话用户接听群发
            $where['chat_type']['$in'][] = 11; //用户送礼
            $where['chat_type']['$in'][] = 21; //APP有VIP登录时，会向随机向10个在线主播发上线信息
            $where['chat_type']['$in'][] = 22; //APP有新入户进入时，会随机向10个在线主播发上线信息
            $where['chat_type']['$in'][] = 23; //平台新用户充值VIP后，会随机向30位在线主播推送信息
            $where['chat_type']['$in'][] = 24; //有主播登录APP后，会向平台已关注该主播的用户推送消息
            $where['chat_type']['$in'][] = 25; //主播设置聊天托管后，自动向新用户推送消息
            $where['chat_type']['$in'][] = 26; //主播设置聊天托管后，自动回复用户消息
            $where['chat_type']['$in'][] = 27; //主播设置聊天托管后，若接收到该类型信息，则向uid主动发送消息
            $where['chat_type']['$in'][] = 28; // 男版一键打招呼；
            $where['chat_type']['$in'][] = 29; //女版用户在开启聊天托管的情况下，上线时，会向目前平台上50名在线男性用户发送聊天托管消息（1.2版本客户端添加定时器）
            $where['chat_type']['$in'][] = 31;// 密友上线提醒
            $where['chat_type']['$in'][] = 33;//用户守护被夺走
            $where['chat_type']['$in'][] = 34;//主播新守护消息
            $where['chat_type']['$in'][] = 40; //主播群发通话时，通知男性用户该主播群发的视频的请求已被人接通;
            $where['chat_type']['$in'][] = 43; //用户新关注发送信息;
            $where['chat_type']['$in'][] = 50; //客服消息
            $where['chat_type']['$in'][] = 42;//新用户拒接套路话术信息
            $where['chat_type']['$in'][] = 44;//用户发送行为托管消息

            $whereOption['sort'] = array('_id' => -1);
            $whereOption['limit'] = 100;
            $records = $mon->find('tb_user_chat_v2', $where, $whereOption);
            if (!empty($records)) {
                $records = array_reverse($records);
                foreach ($records as $v) {
                    unset($v['ip']);
                    unset($v['service_id']);
                    unset($v['channel_number']);
                    unset($v['_id']);
                    unset($v['from']);
                    unset($v['version_code']);
                    unset($v['m_id']);
                    unset($v['look']);
                    $v['audio_time'] = $v['audio_time'] ?? 0;
                    $v['charge_photo'] = $v['charge_photo'] ?? 0;

                    if (in_array($v['content_type'], [1, 2, 3]) && $v['suggestion'] > 0) {
                        //continue;
                    }

                    if (in_array($v['content_type'], array(4, 5))) {
                        if (isset($v['call_data'])) {
                            $v['call_data'] = json_decode($v['call_data'], true);
                        }
                    }

                    if ($v['content_type'] == 6) {
                        $v['gift_data'] = json_decode($v['gift_data'], true);
                    }

                    if ($v['content_type'] == 7) {
                        $v['demand_gift'] = json_decode($v['demand_gift'], true);
                    }

                    $data[] = $v;
                }
            }

            if (!empty($data)) {
                //标记最后拉取时间
                UserChatFlagDao::getInstance()->updateLastTimeFlag($uid, $imei, $micotime);

                foreach ($data as $k1 => $v1) {
                    if ($v1['chat_type'] == 44) {
                        $tmp_uid = $v1['uid'];
                        $data[$k1]['uid'] = $v1['receive_uid'];
                        $data[$k1]['receive_uid'] = $tmp_uid;
                    }

                    $tarUserInfo = User::query()->where('id', $v1['uid'])->first();
                    $tarUserInfo = modelToArray($tarUserInfo);
                    $format = (new MessageAction())->formatUserInfo($tarUserInfo);
                    if (!empty($format) && $format['sex'] == 2) {
                        $call_show_type = $format['call_show_type'];
                        $call_show = $format['call_show'];

                        if ($call_show_type == 1) {
                            $format['video_url'] = $call_show;
                            $format['photo_url'] = '';
                        } elseif ($call_show_type == 2) {
                            $format['video_url'] = '';
                            $format['photo_url'] = $call_show;
                        } else {
                            $format['video_url'] = '';
                            $format['photo_url'] = '';
                        }
                        $format['remarks_name'] = '';
                    } else {
                        $format['video_url'] = '';
                        $format['photo_url'] = '';
                        $remark = UserRemarkDao::getInstance()->getInfo($tarUserInfo['id'], $userInfo['id']);
                        $format['remarks_name'] = !empty($remark) ? $remark['remarks_name'] : '';
                    }
                    $data[$k1]['user_info'] = $format;
                    $data[$k1]['is_hello'] = 0;
                    $data[$k1]['sort_type'] = 0;

                    // 用户亲密度
                    if ($tarUserInfo['sex'] == 1) {
                        $data[$k1]['closeness'] = ClosenessDao::read($v1['uid'], $v1['receive_uid']);
                    } else {
                        $data[$k1]['closeness'] = ClosenessDao::read($v1['receive_uid'], $v1['uid']);
                    }

                }
            }
            $data = array_values($data);
            $res['data'] = $data;
            return $res;
        } catch (Throwable $e) {
            LoggerUtil::write("user_chat_v2_dao", [$uid, $e->getMessage(), $e->getFile(), $e->getLine()]);
        }
    }


}